import json
import random
import re

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from libs.aliyun.sample import Sample
from libs.captcha.captcha import captcha
from utils.constants import IMAGE_CODE_REDIS_EXPIRES
from utils.emails import Email
from utils.response_code import RETCODE
from utils.views import LoginRequiredJsonMixin


class ImgView(View):
    def get(self, request, uuid):
        # 1、生成验证码
        _, text, image = captcha.generate_captcha()
        # 2、将生成的验证码存储到redis数据库里
        redis_conn = get_redis_connection("verifications")
        redis_conn.setex("img_%s" % uuid, IMAGE_CODE_REDIS_EXPIRES, text)
        # 3、返回图片数据
        return http.HttpResponse(image, content_type="image/jpeg")


class EmailsView(LoginRequiredJsonMixin, View):
    def put(self, request):
        # 1、获取传入的邮箱数据
        data_dict = json.loads(request.body)
        email = data_dict.get("email")
        # 2、校验邮箱格式是否正确
        if not (email and re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email)):
            return http.JsonResponse({"code": RETCODE.EMAILERR, "errmsg": "邮箱格式错误"})
        # 3、将数据存入数据库
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            return http.JsonResponse({"code": RETCODE.DBERR, "errmsg": "邮箱保存失败"})
        # 4、发送邮箱验证
        ret = Email.send_email(request, email)
        print(">>>>>>发送邮件>>>>>>", ret)

        return http.JsonResponse({"code": RETCODE.OK, "errmsg": "邮箱保存成功"})


class EmailVerificationsView(View):
    def get(self, request):
        # 1、获取url的token值
        token = request.GET.get("token")
        # 2、校验token是否过期或者为null
        if not token:
            return http.HttpResponseBadRequest('缺少token')
        # 3、验证url是否有效
        user = Email.verify_email(token)
        if not user:
            return http.HttpResponseBadRequest('token无效')
        # 4、修改数据库的email_active值
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            return http.HttpResponseBadRequest('邮箱验证失败')

        return redirect(reverse("user:user_center"))


class SmsView(View):

    def get(self, request, phone):
        # 1、获取数据
        image_code = str(request.GET.get("image_code")).lower()
        uuid = request.GET.get("uuid")

        # 2、校验数据
        if not all([image_code, uuid]):
            return http.HttpResponseBadRequest('缺少必传参数')

        # 3、到redis获取出数据
        redis_con = get_redis_connection("verifications")
        img_data = redis_con.get("img_%s" % uuid)
        print("获取到的img_data", img_data)
        # 1、判断一下是否能正常取出数据
        if img_data is None:
            http.JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": "图形验证失败"})
        # 2、将数据库的值删除
        try:
            redis_con.delete("img_%s" % uuid)
        except Exception as e:
            print(e)
        # 4、校验存储的值是否输入的一致
        if image_code != img_data.decode().lower():
            return http.HttpResponseBadRequest('图片验证码输入有误')

        # 6、生成六位随机数
        test = "%06d" % random.randint(0, 999999)

        # 7、将手机验证码存储到redis里
        try:
            redis_con.setex("phone_%s" % phone, 60, test)
        except Exception as e:
            print(e)
            return http.JsonResponse({"code": RETCODE.SMSCODERR, "errmsg": "验证码发送失败、请稍后再试"})

        print("验证码为------->>>", test)
        # response = Sample.send_img(phone, test)
        # # 6、判断返回的状态码是否200
        # print(response)
        # if response['body']['Message'] != "OK":
        #     return http.HttpResponseBadRequest('验证码发送失败，请稍后再试')

        # return http.JsonResponse({"code": RETCODE.OK, "errmsg": response['body']['Message']})
        return http.JsonResponse({"code": RETCODE.OK, "errmsg": "验证码已发送"})
